import { ApiCall } from "tsrpc";
import { ReqReadMail, ResReadMail } from "../../../../shared/master/body/mail/PtlReadMail";
import { player } from "../../../../model/fight/body/player";
import { Tpl_mailRead, template } from "../../../../shared/master/MsgAction";
import app from "../../../../app";
import server_mail from "../../../../server_mail";
import { logger } from "../../../../model/server/logger";

export default async function (call: ApiCall<ReqReadMail, ResReadMail>) {
    call.succ({})
    let user = call.req._player as player;
    let readItem = user.mail.shift();
    if (!readItem) {
        user.sendMsg(template.default, `暂时还没有你的邮件噢~`);
        server_mail.c_http.callApi('Pull', { uuid: user.uuid, dev: user.mail_serverDev }).then((req) => {
            if (req.isSucc) {
                let list = req.res.list
                if (list.length > 0) {
                    user.mail.push(...list)
                }
                user.mail_serverDev = req.res.dev;
            } else {
                logger.error('邮箱服务器请求失败')
            }
        })
        return;
    }
    let bag = user.getBag();
    let annexs:{name:string,cont:number}[] = [];
    for (let i = 0; i < readItem.annexs.length; i++) {
        const element = readItem.annexs[i];
        const item = app.createItem(element)
    
        bag.add(item)
        annexs.push({
            name: item.getStyleName(),
            cont: item.num
        })
    }

    let tpl:Tpl_mailRead = {
        create:readItem.create,
        from: readItem.from,
        title: readItem.title,
        content: readItem.content,
        annexs: annexs
    }
    
    user.sendMsg(template.mailRead,tpl)
}